import 'package:flutter/material.dart';

import 'package:flutter_channel_demo/api/send.dart';
import 'package:flutter_channel_demo/widgets/empty.dart';
import 'package:flutter_channel_demo/widgets/sendItem.dart';

import 'package:flutter_channel_demo/widgets/top_filter.dart';

class SendListPage extends StatefulWidget {
  const SendListPage({super.key});

  @override
  State<SendListPage> createState() => _SendListPageState();
}

class _SendListPageState extends State<SendListPage>
    with AutomaticKeepAliveClientMixin {
  ScrollController scrollController = ScrollController();

  final GlobalKey _stackKey = GlobalKey();

  // final List<String> _dropDownHeaderItemStrings = ['全部'];

  List<dynamic> fullTenants = []; //用工单位

  List<dynamic> sendList = []; //派遣列表

  int pageIndex = 1; //页码

  bool _loading = false; // 是否正在加载数据

  bool hasMore = true; //是否有下一页

  bool fiterOpened = false; //筛选面板展开

  bool initLoading = true; //页面初始化loading

  @override
  void initState() {
    _loadTenants();

    super.initState();
    scrollController.addListener(() {
      // 滑动距离
      var dis = scrollController.position.maxScrollExtent -
          scrollController.position.pixels;
      // 当滑动到底部不足 300 并且没有加载数据时，加载更多
      // 也可以根据临界值，是否允许下拉刷新以及下拉加载更多
      if (dis < 300 && !_loading && hasMore) {
        _loadData(loadMore: true);
      }
    });

    _loadData();
  }

  @override
  void dispose() {
    super.dispose();
    // 释放资源
    scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        appBar: AppBar(title: const Text('我的工作')),
        body: initLoading
            ? const Center(
                child: SizedBox(
                  height: 50.0,
                  width: 50.0,
                  child: CircularProgressIndicator(
                    value: null,
                    strokeWidth: 7.0,
                  ),
                ),
              )
            : TopFilter(
                stackKey: _stackKey,
                showAll: true,
                options: fullTenants,
                content: contentBuilder(),
                itemTap: (condition) {
                  _loadData(loadMore: false, tenant: condition?.value);
                },
              ));
  }

//列表内容区
  Widget contentBuilder() {
    if (_loading) {
      return const Padding(padding: EdgeInsets.all(10.0));
    }
    if (sendList.isNotEmpty) {
      return Expanded(
          child: FutureBuilder<List<String>>(builder: (context, snapshot) {
        return RefreshIndicator(
            onRefresh: _loadData,
            child: ListView.builder(
                itemBuilder: (context, index) => sendItem(
                    context: context, sendList: sendList, index: index),
                itemCount: sendList.length,
                controller: scrollController));
      }));
    }
    return const Empty(
      emptyLabel: '暂无工作记录',
    );
  }

  Future<void> _loadData({loadMore = false, tenant = ''}) async {
    if (!loadMore) {
      setState(() {
        pageIndex = 1;
      });
    }
    try {
      // 访问网络
      int currentIndex = pageIndex + (loadMore ? 1 : 0);
      var result = await fetchList((currentIndex - 1) * 10, tenant, context);
      List<dynamic> list = result['data']['list'];

      // 更新数据
      setState(() {
        _loading = false;
        hasMore = list.length == 10;
        if (loadMore) {
          sendList = [...sendList, ...list];
          pageIndex = pageIndex + 1;
        } else {
          sendList = list;
        }
      });
    } catch (e) {
      setState(() {
        _loading = false;
      });
    }
  }

//获取用工单位
  Future<void> _loadTenants() async {
    try {
      var result = await fetchWorkerTenants(context);
      List<dynamic> list = result['list'];
      setState(() {
        fullTenants = list;
        initLoading = false;
      });
    } catch (e) {
      setState(() {
        fullTenants = [];
        initLoading = false;
      });
    }
  }

  @override
  bool get wantKeepAlive => false;
}
